package com.gec.config;

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import com.gec.common.BaseContext;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;

/**MybatisPlus的分页插件
 *
 * @author : [chenxys]
 * @version : [v1.0]
 */
@Configuration
public class MybatisPlusConfig {

    /**配置MybatisPlus的分页插件
     *
     * @author chenxys
     * @return com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor
     */
    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor(){
        MybatisPlusInterceptor mybatisPlusInterceptor = new MybatisPlusInterceptor();
        mybatisPlusInterceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
        return mybatisPlusInterceptor;
    }

    /**
     * 配置自动插入
     * @author chenxys
     * @return com.baomidou.mybatisplus.core.handlers.MetaObjectHandler
     */
    @Bean
    public MetaObjectHandler metaObjectHandler(){
        return new MetaObjectHandler() {
            @Override
            public void insertFill(MetaObject metaObject) {
                this.setFieldValByName("createTime", LocalDateTime.now(),metaObject);
                this.setFieldValByName("updateTime", LocalDateTime.now(),metaObject);
                this.setFieldValByName("status", 0,metaObject);
                this.setFieldValByName("createUser", BaseContext.getCurrentId(),metaObject);
                this.setFieldValByName("updateUser", BaseContext.getCurrentId(),metaObject);
            }

            @Override
            public void updateFill(MetaObject metaObject) {
                this.setFieldValByName("updateTime", LocalDateTime.now(),metaObject);
                this.setFieldValByName("updateUser", BaseContext.getCurrentId(),metaObject);
            }
        };
    }
}
